<template>
  <div class="supplier-performance-container">
    <div class="page-header">
      <h2 class="page-title">供应商合作绩效看板</h2>
      <div class="header-actions">
        <el-select v-model="selectedYear" placeholder="选择年份" @change="handleYearChange">
          <el-option
            v-for="year in yearOptions"
            :key="year"
            :label="year + '年'"
            :value="year"
          />
        </el-select>
        <el-select v-model="selectedQuarter" placeholder="选择季度" @change="handleQuarterChange">
          <el-option
            v-for="quarter in quarterOptions"
            :key="quarter.value"
            :label="quarter.label"
            :value="quarter.value"
          />
        </el-select>
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>刷新数据
        </el-button>
        <el-button type="primary" plain @click="exportReport">
          <el-icon><Download /></el-icon>导出报告
        </el-button>
      </div>
    </div>
    
    <!-- 绩效统计卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card">
        <div class="stat-icon" style="background-color: #409EFF;">
          <el-icon><Star /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-title">A级供应商</div>
          <div class="stat-value">{{ performanceStats.levelA }}</div>
          <div class="stat-trend" :class="{ 'up': performanceStats.levelATrend > 0, 'down': performanceStats.levelATrend < 0 }">
            <el-icon v-if="performanceStats.levelATrend > 0"><CaretTop /></el-icon>
            <el-icon v-else-if="performanceStats.levelATrend < 0"><CaretBottom /></el-icon>
            <span>{{ Math.abs(performanceStats.levelATrend) }}%</span>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-icon" style="background-color: #67C23A;">
          <el-icon><GoodsFilled /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-title">平均交付准时率</div>
          <div class="stat-value">{{ performanceStats.onTimeDelivery }}%</div>
          <div class="stat-trend" :class="{ 'up': performanceStats.onTimeDeliveryTrend > 0, 'down': performanceStats.onTimeDeliveryTrend < 0 }">
            <el-icon v-if="performanceStats.onTimeDeliveryTrend > 0"><CaretTop /></el-icon>
            <el-icon v-else-if="performanceStats.onTimeDeliveryTrend < 0"><CaretBottom /></el-icon>
            <span>{{ Math.abs(performanceStats.onTimeDeliveryTrend) }}%</span>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-icon" style="background-color: #E6A23C;">
          <el-icon><Warning /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-title">平均质量合格率</div>
          <div class="stat-value">{{ performanceStats.qualityRate }}%</div>
          <div class="stat-trend" :class="{ 'up': performanceStats.qualityRateTrend > 0, 'down': performanceStats.qualityRateTrend < 0 }">
            <el-icon v-if="performanceStats.qualityRateTrend > 0"><CaretTop /></el-icon>
            <el-icon v-else-if="performanceStats.qualityRateTrend < 0"><CaretBottom /></el-icon>
            <span>{{ Math.abs(performanceStats.qualityRateTrend) }}%</span>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-icon" style="background-color: #F56C6C;">
          <el-icon><Money /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-title">采购成本节约</div>
          <div class="stat-value">{{ performanceStats.costSaving }}万</div>
          <div class="stat-trend" :class="{ 'up': performanceStats.costSavingTrend > 0, 'down': performanceStats.costSavingTrend < 0 }">
            <el-icon v-if="performanceStats.costSavingTrend > 0"><CaretTop /></el-icon>
            <el-icon v-else-if="performanceStats.costSavingTrend < 0"><CaretBottom /></el-icon>
            <span>{{ Math.abs(performanceStats.costSavingTrend) }}%</span>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 图表区域 -->
    <div class="chart-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>供应商等级分布</span>
              </div>
            </template>
            <div class="chart-container-wrapper">
            <div id="supplierLevelChart" class="chart-container"></div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>绩效评分趋势</span>
              </div>
            </template>
            <div class="chart-container-wrapper">
            <div id="performanceTrendChart" class="chart-container"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>各维度评分对比</span>
              </div>
            </template>
            <div class="chart-container-wrapper">
            <div id="dimensionComparisonChart" class="chart-container"></div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>问题分布统计</span>
              </div>
            </template>
            <div class="chart-container-wrapper">
            <div id="issueDistributionChart" class="chart-container"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 供应商绩效排名 -->
    <el-card class="ranking-card">
      <template #header>
        <div class="card-header">
          <span>供应商绩效排名 TOP 10</span>
          <el-radio-group v-model="rankingType" size="small" @change="handleRankingTypeChange">
            <el-radio-button value="score" label="综合评分"></el-radio-button>
            <el-radio-button value="delivery" label="交付表现"></el-radio-button>
            <el-radio-button value="quality" label="质量表现"></el-radio-button>
            <el-radio-button value="cost" label="成本表现"></el-radio-button>
          </el-radio-group>
        </div>
      </template>
      
      <el-table :data="supplierRanking" stripe style="width: 100%">
        <el-table-column prop="rank" label="排名" width="80" align="center" />
        <el-table-column prop="name" label="供应商名称" min-width="180" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="level" label="等级" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)">{{ row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="综合评分" width="100" align="center">
          <template #default="{ row }">
            <div class="score-cell">
              <span>{{ row.score }}</span>
              <div class="score-bar" :style="{ width: row.score + '%', backgroundColor: getScoreColor(row.score) }"></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryScore" label="交付评分" width="100" align="center" />
        <el-table-column prop="qualityScore" label="质量评分" width="100" align="center" />
        <el-table-column prop="costScore" label="成本评分" width="100" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewSupplierDetail(row)">
              <el-icon><View /></el-icon>详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue'
import * as echarts from 'echarts'
import { 
  Refresh, Download, Star, CaretTop, CaretBottom,
  GoodsFilled, Warning, Money, View
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { ChartResizer } from '../../../utils/chartResize'

// 图表实例
let supplierLevelChart: echarts.ECharts | null = null
let performanceTrendChart: echarts.ECharts | null = null
let dimensionComparisonChart: echarts.ECharts | null = null
let issueDistributionChart: echarts.ECharts | null = null

// 筛选条件
const selectedYear = ref(new Date().getFullYear())
const selectedQuarter = ref('Q1')
const yearOptions = [
  selectedYear.value - 2,
  selectedYear.value - 1,
  selectedYear.value
]
const quarterOptions = [
  { value: 'Q1', label: '第一季度' },
  { value: 'Q2', label: '第二季度' },
  { value: 'Q3', label: '第三季度' },
  { value: 'Q4', label: '第四季度' }
]

// 绩效统计数据
const performanceStats = reactive({
  levelA: 28,
  levelATrend: 5.2,
  onTimeDelivery: 94.5,
  onTimeDeliveryTrend: 1.8,
  qualityRate: 97.2,
  qualityRateTrend: -0.5,
  costSaving: 325.6,
  costSavingTrend: 12.3
})

// 排名类型
const rankingType = ref('score')

// 供应商排名数据
const supplierRanking = ref([
  {
    rank: 1,
    name: '上海博世汽车部件有限公司',
    category: '原材料供应商',
    level: 'A级',
    score: 96.5,
    deliveryScore: 98.2,
    qualityScore: 97.5,
    costScore: 94.8
  },
  {
    rank: 2,
    name: '深圳市华为技术有限公司',
    category: '设备供应商',
    level: 'A级',
    score: 95.8,
    deliveryScore: 96.0,
    qualityScore: 98.2,
    costScore: 93.5
  },
  {
    rank: 3,
    name: '德国西门子(中国)有限公司',
    category: '设备供应商',
    level: 'A级',
    score: 94.3,
    deliveryScore: 95.5,
    qualityScore: 96.8,
    costScore: 91.2
  },
  {
    rank: 4,
    name: '日本电产(大连)有限公司',
    category: '原材料供应商',
    level: 'A级',
    score: 93.7,
    deliveryScore: 94.2,
    qualityScore: 95.6,
    costScore: 92.1
  },
  {
    rank: 5,
    name: '中国石化上海石油化工股份有限公司',
    category: '原材料供应商',
    level: 'A级',
    score: 92.5,
    deliveryScore: 93.0,
    qualityScore: 94.8,
    costScore: 90.5
  },
  {
    rank: 6,
    name: '京东方科技集团股份有限公司',
    category: '原材料供应商',
    level: 'B级',
    score: 91.8,
    deliveryScore: 92.5,
    qualityScore: 93.2,
    costScore: 89.8
  },
  {
    rank: 7,
    name: '比亚迪股份有限公司',
    category: '原材料供应商',
    level: 'B级',
    score: 90.6,
    deliveryScore: 91.8,
    qualityScore: 92.5,
    costScore: 88.4
  },
  {
    rank: 8,
    name: '顺丰速运有限公司',
    category: '物流供应商',
    level: 'B级',
    score: 89.5,
    deliveryScore: 95.2,
    qualityScore: 88.6,
    costScore: 86.2
  },
  {
    rank: 9,
    name: '上海宝钢包装股份有限公司',
    category: '包装材料供应商',
    level: 'B级',
    score: 88.7,
    deliveryScore: 89.5,
    qualityScore: 90.2,
    costScore: 87.1
  },
  {
    rank: 10,
    name: '中国联合网络通信有限公司',
    category: '服务供应商',
    level: 'B级',
    score: 87.9,
    deliveryScore: 88.6,
    qualityScore: 89.5,
    costScore: 86.4
  }
])

// 根据等级获取标签类型
const getLevelTagType = (level: string) => {
  switch (level) {
    case 'A级': return 'success'
    case 'B级': return 'warning'
    case 'C级': return 'info'
    case 'D级': return 'danger'
    default: return ''
  }
}

// 根据分数获取颜色
const getScoreColor = (score: number) => {
  if (score >= 90) return '#67C23A'
  if (score >= 80) return '#E6A23C'
  if (score >= 70) return '#F56C6C'
  return '#909399'
}

// 处理年份变化
const handleYearChange = () => {
  refreshData()
}

// 处理季度变化
const handleQuarterChange = () => {
  refreshData()
}

// 处理排名类型变化
const handleRankingTypeChange = () => {
  // 根据不同排名类型重新排序
  if (rankingType.value === 'score') {
    supplierRanking.value.sort((a, b) => b.score - a.score)
  } else if (rankingType.value === 'delivery') {
    supplierRanking.value.sort((a, b) => b.deliveryScore - a.deliveryScore)
  } else if (rankingType.value === 'quality') {
    supplierRanking.value.sort((a, b) => b.qualityScore - a.qualityScore)
  } else if (rankingType.value === 'cost') {
    supplierRanking.value.sort((a, b) => b.costScore - a.costScore)
  }
  
  // 更新排名
  supplierRanking.value.forEach((item, index) => {
    item.rank = index + 1
  })
}

// 刷新数据
const refreshData = () => {
  ElMessage.success(`已加载${selectedYear.value}年${selectedQuarter.value}数据`)
  
  // 重新初始化图表
  initSupplierLevelChart()
  initPerformanceTrendChart()
  initDimensionComparisonChart()
  initIssueDistributionChart()
}

// 查看供应商详情
const viewSupplierDetail = (row: any) => {
  ElMessage.info(`查看供应商 ${row.name} 的详细绩效信息`)
}

// 导出报告
const exportReport = () => {
  ElMessage.success(`${selectedYear.value}年${selectedQuarter.value}供应商绩效报告导出成功`)
}

// 初始化供应商等级分布图表
const initSupplierLevelChart = () => {
  const chartDom = document.getElementById('supplierLevelChart')
  if (!chartDom) return
  
  supplierLevelChart = echarts.init(chartDom)
  
  // 注册到ChartResizer以实现自适应
  ChartResizer.getInstance().register('supplierLevelChart', supplierLevelChart, chartDom)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ['A级', 'B级', 'C级', 'D级']
    },
    series: [
      {
        name: '供应商等级',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 28, name: 'A级' },
          { value: 45, name: 'B级' },
          { value: 86, name: 'C级' },
          { value: 32, name: 'D级' }
        ]
      }
    ]
  }
  
  supplierLevelChart.setOption(option)
}

// 初始化绩效评分趋势图表
const initPerformanceTrendChart = () => {
  const chartDom = document.getElementById('performanceTrendChart')
  if (!chartDom) return
  
  performanceTrendChart = echarts.init(chartDom)
  
  // 注册到ChartResizer以实现自适应
  ChartResizer.getInstance().register('performanceTrendChart', performanceTrendChart, chartDom)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['综合评分', '交付评分', '质量评分', '成本评分']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value',
      min: 80,
      max: 100
    },
    series: [
      {
        name: '综合评分',
        type: 'line',
        stack: 'Total',
        data: [88.5, 89.2, 90.1, 91.5, 92.8, 93.6],
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        emphasis: {
          focus: 'series'
        }
      },
      {
        name: '交付评分',
        type: 'line',
        stack: 'Total',
        data: [91.2, 92.5, 93.1, 92.8, 94.2, 95.1],
        emphasis: {
          focus: 'series'
        }
      },
      {
        name: '质量评分',
        type: 'line',
        stack: 'Total',
        data: [94.5, 95.2, 94.8, 96.1, 97.2, 97.5],
        emphasis: {
          focus: 'series'
        }
      },
      {
        name: '成本评分',
        type: 'line',
        stack: 'Total',
        data: [85.2, 86.5, 87.2, 88.5, 89.1, 90.2],
        emphasis: {
          focus: 'series'
        }
      }
    ]
  }
  
  performanceTrendChart.setOption(option)
}

// 初始化各维度评分对比图表
const initDimensionComparisonChart = () => {
  const chartDom = document.getElementById('dimensionComparisonChart')
  if (!chartDom) return
  
  dimensionComparisonChart = echarts.init(chartDom)
  
  // 注册到ChartResizer以实现自适应
  ChartResizer.getInstance().register('dimensionComparisonChart', dimensionComparisonChart, chartDom)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['A级供应商', 'B级供应商', 'C级供应商', 'D级供应商']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      min: 60,
      max: 100
    },
    yAxis: {
      type: 'category',
      data: ['交付准时率', '质量合格率', '成本控制', '服务响应', '创新能力']
    },
    series: [
      {
        name: 'A级供应商',
        type: 'bar',
        data: [95.2, 97.5, 92.8, 94.5, 90.2]
      },
      {
        name: 'B级供应商',
        type: 'bar',
        data: [90.5, 92.8, 88.5, 89.2, 85.5]
      },
      {
        name: 'C级供应商',
        type: 'bar',
        data: [85.2, 87.5, 82.8, 84.5, 78.2]
      },
      {
        name: 'D级供应商',
        type: 'bar',
        data: [75.5, 80.2, 72.5, 76.8, 68.5]
      }
    ]
  }
  
  dimensionComparisonChart.setOption(option)
}

// 初始化问题分布图表
const initIssueDistributionChart = () => {
  const chartDom = document.getElementById('issueDistributionChart')
  if (!chartDom) return
  
  issueDistributionChart = echarts.init(chartDom)
  
  // 注册到ChartResizer以实现自适应
  ChartResizer.getInstance().register('issueDistributionChart', issueDistributionChart, chartDom)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '问题分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 35, name: '交付延迟' },
          { value: 28, name: '质量缺陷' },
          { value: 15, name: '价格波动' },
          { value: 12, name: '沟通不畅' },
          { value: 10, name: '其他问题' }
        ]
      }
    ]
  }
  
  issueDistributionChart.setOption(option)
}

// 组件挂载后初始化图表
onMounted(() => {
  initSupplierLevelChart()
  initPerformanceTrendChart()
  initDimensionComparisonChart()
  initIssueDistributionChart()
  
  // 不再需要手动监听窗口大小变化，由ChartResizer处理
})

// 组件卸载前清理资源
onBeforeUnmount(() => {
  // 从ChartResizer中注销图表
  if (supplierLevelChart) {
    ChartResizer.getInstance().unregister('supplierLevelChart')
    supplierLevelChart.dispose()
  }
  
  if (performanceTrendChart) {
    ChartResizer.getInstance().unregister('performanceTrendChart')
    performanceTrendChart.dispose()
  }
  
  if (dimensionComparisonChart) {
    ChartResizer.getInstance().unregister('dimensionComparisonChart')
    dimensionComparisonChart.dispose()
  }
  
  if (issueDistributionChart) {
    ChartResizer.getInstance().unregister('issueDistributionChart')
    issueDistributionChart.dispose()
  }
})
</script>

<style scoped>
.supplier-performance-container {
  padding: var(--content-padding);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  padding: 15px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.stat-icon .el-icon {
  font-size: 32px;
  color: white;
}

.stat-content {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.stat-trend.up {
  color: #67C23A;
}

.stat-trend.down {
  color: #F56C6C;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 0;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container-wrapper {
  position: relative;
  height: 350px;
}

.chart-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.ranking-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.score-cell {
  position: relative;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.score-bar {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  z-index: 0;
  opacity: 0.2;
  border-radius: 10px;
}

.score-cell span {
  position: relative;
  z-index: 1;
}

/* 响应式布局 */
@media (max-width: 1400px) {
  .stat-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .stat-cards {
    grid-template-columns: 1fr;
  }
  
  .chart-container-wrapper {
    height: 300px;
  }
}
</style> 